<?php
namespace app\admin\controller;
use app\common\controller\AdminBase;
require_once dirname(dirname(__FILE__)).'../../../vendor/aliyun-php-sdk/aliyun-php-sdk-core/Config.php';   // 假定您的源码文件和aliyun-php-sdk处于同一目录
use think\Cache;
use vod\Request\V20170321 as vod;
require_once APP_PATH . '/../extend/aliyun-oss-php-sdk-master/autoload.php'; //引入阿里云OSS SDK，注意替换路径
use OSS\Core\OssException;
use OSS\OssClient;
use OSS\Core\OssUtil;

/**
 * Class Account 教育云控制器类
 * www.yunknet.cn
 */

class Educloud extends AdminBase{
    /**
     * 账户信息页面
     */
    public function liveIndex(){
        $info=$this->get_site_info(2);
        $liveurl=$info['server']."/educloud/educloud/getLiveCountInfo";
        $liverestemp=post_curl($liveurl,$info);
        $liveresult=json_decode($liverestemp,true);
        if($liveresult['code']==0){
            $liveresult['data']['remain']=floor((strtotime($liveresult['data']['expire_time'])-strtotime(date('Y-m-d h:i:s', time())))/86400);
            $this->assign("liveoinfo",$liveresult['data']);
            $DayPeakUserurl=$info['server']."/educloud/educloud/getDayPeakUser";
            $DayPeakUser=json_decode(post_curl($DayPeakUserurl,$info),true);
            $TodyPeakUser=$DayPeakUser['data']['peak_user'][date('Y-m-d', time())];
            $time=array();
            $num=array();
            foreach($DayPeakUser['data']['peak_user'] as $key=>$v)
            {
                $time[]=$key;$num[]=$v;
            }
            $str_num= json_encode($num);
            $str_time = json_encode($time);
            $this->assign("liveinfo",$liveresult);
            $this->assign('str_num', $str_num);
            $this->assign('str_time', $str_time);
            $this->assign('TodyPeakUser', $TodyPeakUser);
        }else{
            $this->assign("liveinfo",$liveresult);
        }
        return $this->fetch('index');
    }
    /**
     * 绑定教育云直播账户
     */
    public function liveBind(){
        if ($this->request->isPost()) {
            $data = [];
            foreach ($this->request->param() as $k => $v) {
                $data[] = ['name' => $k, 'value' => $v];
            }
            if ($this->saveAll('system', $data) === true) {
                clear_cache();
                insert_admin_log('绑定教育云直播账户');
                $this->success('保存成功',url('admin/educloud/liveBind'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        $data = [];
        foreach (model('system')->select() as $v) {
            $data[$v['name']] = $v['value'];
        }
        return $this->fetch('liveBind', ['data' => $data]);
    }
    /**
     * 直播账号详情
     */
    public function liveset(){
        $info = $this->get_site_info(2);
        if(empty($info['partner_id'])||empty($info['partner_key'])){
            $this->redirect('admin/educloud/liveBind');
        }
        $url = config('author_web') . "/educloud/educloud/getLiveCountInfo";
        $url2 = config('author_web') . "/educloud/educloud/getDayPeakUser";
        $postdata = ['domain' => $info['domain'], 'authorcode' => $info['authorcode'], 'partner_id' => $info['partner_id'], 'partner_key' => $info['partner_key'], 'private_domain' => $info['private_domain']];
        $res=json_decode(post_curl($url, $postdata),true);
        $res['data']['remain']=round((strtotime($res['data']['expire_time'])-time())/3600/24);
        $end_date=date('Y-m-d',time());
        $start_date=date("Y-m-d",strtotime("-7 day"));
        $postdata2 = ['domain' => $info['domain'], 'authorcode' => $info['authorcode'], 'partner_id' => $info['partner_id'], 'partner_key' => $info['partner_key'], 'private_domain' => $info['private_domain'],'start_date' => $start_date,'end_date' => $end_date];
        $PeakUser=json_decode(post_curl($url2, $postdata2),true);
        foreach ($PeakUser['data']['peak_user'] as $k=> $value) {
            $PeakUserList[]=$value;
            $PeakTmmeList[]=$k;
        }
        return $this->fetch('liveset',['res'=>$res,'PeakUserList'=>json_encode($PeakUserList),'PeakTmmeList'=>json_encode($PeakTmmeList)]);
    }
    /**
     * 绑定教育云点播账户
     */
    public function videoBind()
    {
        if ($this->request->isPost()) {
            $data = [];
            foreach ($this->request->param() as $k => $v) {
                $data[] = ['name' => $k, 'value' => $v];
            }
            if ($this->saveAll('system', $data) === true) {
                $admindata=model('admin')->field('id')->select();
                foreach($admindata as $k => $v){
                    db('admin')->where(['id'=>$admindata[$k]['id']])->update(['category_id'=>'']);
                }
                $this->success('保存成功',url('admin/educloud/videoList'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        $data = [];
        foreach (model('system')->select() as $v) {
            $data[$v['name']] = $v['value'];
        }
        return $this->fetch('videoBind', ['data' => $data]);
    }
    /**
     * 点播账号信息
     */
    public function videoset(){
        $info = $this->get_site_info(1);

        return $this->fetch('videoset');
    }
    /**
     * 教育云点播视频列表
     */
    public function videoList()
    {
        $this->redisReturn()->del('time');
        $param = $this->request->param();
        $where = [];
        if (isset($param['type_id'])) {
            $where['type_id'] = $param['type_id'];
        }
        $list = model('video')->order('id desc')
            ->where($where)
            ->paginate(config('page_number'), false, ['query' => $param]);
        return $this->fetch('videoList',['videocategory'=>model('videoType')->select(),'list'=>model('video')->select(),'count'=>10,'PageSize'=>config('PageSize'),'curr'=>1,'list'=>$list]);
        // if(empty($info['KeyID'])||empty($info['KeySecret'])){
        //     $this->redirect('admin/educloud/videoBind');
        // }
//        $param = $this->request->param();
//        $teacherinfo=model('admin')->where(['id'=>is_admin_login()])->find();
//        $category_id=$teacherinfo['category_id'];
//        if(empty($category_id)){
//            $res=$this->addCategoryPhpSDK($teacherinfo['username'],config('root_category_id'));
//            if(!empty($res['Category']['CateId'])){
//                db('admin')->where(['id'=>is_admin_login()])->update(['category_id' => $res['Category']['CateId']]);
//            }else{
//                $this->error($res['msg']);
//            }
//        }
//        if(!empty($param['CateId'])){
//            $category_id=$param['CateId'];
//        }
//        $url = $info['server'] . "/educloud/alivideo/getvideolist";
//        $postdata = ['private_domain'=>$info['private_domain'],'domain'=>$info['domain'],'authorcode'=>$info['authorcode'],'KeyID' => $info['KeyID'], 'keySecret' => $info['KeySecret'], 'PageSize' => config('PageSize'),'PageNo'=>$param['page'],'aliyuncategory'=>$category_id];
//        $restemp = json_to_array(post_curl($url, $postdata));
//        $videocategory=$this->getVideoCategory(1,100);
//        return $this->fetch('videoList', ['list' => $restemp['VideoList']['Video'],'curr'=>$param['page'],'count'=>$restemp['Total'],'PageSize'=>config('PageSize'),'videocategory'=>$videocategory['SubCategories']['Category']]);
    }
    /**
     * 删除视频
     * @param client 发送请求客户端
     * @return DeleteVideoResponse 删除视频响应数据
     */
    public function deleteVideos($client, $videoIds) {
        $request = new vod\DeleteVideoRequest();
        $request->setVideoIds($videoIds);   // 支持批量删除视频；videoIds为传入的视频ID列表，多个用逗号分隔
        $request->setAcceptFormat('JSON');
        return $client->getAcsResponse($request);
    }

    /**
     * 删除教育云视频
     */
    public function videodel()
    {
        $param = $this->request->param();
//        $data = model('video')->where(['id'=>['in',$param['id']]])->select();
////        try {
////            $client = $this->initVodClient('LTAI4FcncugJ3cXhfc4TYLx3', 'oizfnpEr3XOc8lovUQBJjXDoEfu6iS');
////            $delInfo = $this->deleteVideos($client, implode(',',array_column($data,'video_id')));
////        } catch (Exception $e) {
////            print $e->getMessage()."\n";
////        }
        $flg = model('video')->where(['id'=>['in',$param['id']]])->delete();
        if($flg){
            $this->success('删除成功',url('admin/educloud/videoList'));
        }else{
            $this->error('删除失败',url('admin/educloud/videoList'));
        }
    }

    /**
     * 上传教育云视频
     */
    public function videoup()
    {
        $this->redisReturn()->del('time');
        $videocategory=model('videoType')->select();
        return $this->fetch('videoup',['videocategory'=>$videocategory,'aliUid'=>config('AliUserId')]);
    }
    /**
     * 视频分类列表
     */
    public function videocategory(){
        $param = $this->request->param();
        $list = model('videoType')->order('id desc')
            ->paginate(config('page_number'), false, ['query' => $param]);
        return $this->fetch('videocategory', ['list' => $list]);
    }
    public function editcategory(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = model('videoType')->where(['id'=>$param['id']])->update(['type_name'=>$param['type_name']]);
            if ($result) {
                insert_admin_log('修改了分类');
                $this->success('修改成功', url('admin/educloud/videocategory'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('save', ['data' => model('videoType')->get(input('id'))]);

    }
    public function getvideoCategory($curr,$PageSize){
        $url = config('author_web') . "/educloud/alivideo/getCategory";
        $category_id = model('admin')->where(['id' => is_admin_login()])->value('category_id');
        $postdata = ['KeyID' => config('KeyID'), 'keySecret' => config('KeySecret'),'CateId'=>$category_id,'PageNo'=>$curr,'PageSize'=>$PageSize];
        $restemp = json_to_array(post_curl($url, $postdata));
        return $restemp;
    }
    /**
     * 删除教育云视频分类
     */
    public function delvideocategory(){
        $param=$this->request->param();
        $url = config('author_web') . "/educloud/alivideo/delCategory";
        $postdata = ['KeyID' => config('KeyID'), 'keySecret' => config('KeySecret'),'CateId'=>$param['id']];
        json_to_array(post_curl($url, $postdata));
        $this->success('删除成功');
    }

    /**
     * 添加教育云视频分类
     */
    public function addvideocategory(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $res = model('videoType')->insert(['type_name'=>$param['type_name']]);
            //$res = $this->addCategoryPhpSDK($param['name'], $category_id);
            if ($res) {
                $this->success('创建成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('addvideocategory');
    }
    public function del($id){
        $res = model('videoType')->where(['id'=>$id])->delete();
        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error($this->errorMsg);
        }
    }
    /**
     * 远程添加教育云视频子分类
     */
    public function addCategoryPhpSDK($name,$ParentId){
        $info=$this->get_site_info(1);
        $url = config('author_web') . "/educloud/alivideo/AddCategoryPhpSDK";
        $postdata = ['domain'=>$info['domain'],'authorcode'=>$info['authorcode'],'KeyID' => $info['KeyID'], 'keySecret' => $info['KeySecret'],'CateName'=>$name,'ParentId'=>$ParentId];
        $restemp = json_to_array(post_curl($url, $postdata));
        return $restemp;
    }

    /**
     * 删除OSS上的文件
     */
    public function ossdel()
    {
        if ($this->request->isPost()) {
            $data=model('Material')->where(['id'=>input('id')])->field('oss_name')->find();
            $ossClient =$this->new_oss();
            $ossClient->deleteObject(config('Bucket'), $data['oss_name']);
            if ($this->delete('Material', $this->request->param()) === true) {
                insert_admin_log('删除资料');
                $this->success('删除成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
    }
    /**
     * 获取上传教育云视频凭证
     */
    public function getaliuptoken()
    {
        $info=$this->get_site_info(1);
        $param = $this->request->param();
        if(empty($param['categoryId'])){
            $category_id=model('admin')->where(['id'=>is_admin_login()])->value('category_id');
        }else{
            $category_id=$param['categoryId'];
        }
        $url=config('author_web')."/educloud/alivideo/getaliuptoken";
        $postdata = ['private_domain'=>$info['private_domain'],'domain'=>$info['domain'],'authorcode'=>$info['authorcode'],'KeyID' => $info['KeyID'], 'keySecret' => $info['KeySecret'], 'filename' =>input('post.title'),'CateId'=>$category_id];
        echo post_curl($url, $postdata);
    }
    /**
     * 获取视频上传地址和凭证
     * @param client 发送请求客户端
     * @return CreateUploadVideoResponse 获取视频上传地址和凭证响应数据
     */
    public function createUploadVideo($client,$title) {
        $request = new vod\CreateUploadVideoRequest();
        $request->setTitle($title);
        $request->setFileName("videoFile.mov");
        $request->setDescription("Video Description");
        $request->setCoverURL("http://img.alicdn.com/tps/TB1qnJ1PVXXXXXCXXXXXXXXXXXX-700-700.png");
        $request->setTags("tag1,tag2");
        $request->setAcceptFormat('JSON');
        return $client->getAcsResponse($request);
    }

    /**
     * 消息点播  对象初始化
     * @param $accessKeyId
     * @param $accessKeySecret
     * @return \DefaultAcsClient
     */
    public function initVodClient($accessKeyId, $accessKeySecret) {
        $regionId = 'cn-shanghai';  // 点播服务接入区域
        $profile = \DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
        return new \DefaultAcsClient($profile);
    }

    /**
     * 消息点播将 type_id 和 视频唯一表示加入队列
     * @return CreateUploadVideoResponse
     */
    public function test(){
        $title = input('title');
        $type_id = input('type_id');
        try {
            $client = $this->initVodClient('LTAI4FcncugJ3cXhfc4TYLx3', 'oizfnpEr3XOc8lovUQBJjXDoEfu6iS');
            $uploadInfo = $this->createUploadVideo($client,$title);
            $redis = new \Redis();
            $redis->connect('127.0.0.1',6379);
            $redis->lPush('videoUpload',$uploadInfo->VideoId.'_'.$type_id);
            return $uploadInfo;
        } catch (\Exception $e) {
            print $e->getMessage()."\n";
        }
    }
    /**
     * 视频信息添加到数据库
     */
//    public function insertVideo(){
//        sleep(15);//由于视频转码。睡眠十五秒
//        $type_id = input('type_id');
//        $redis = new \Redis();
//        $redis->connect('127.0.0.1',6379);
//        $admin_id = $_SESSION['think']['admin_auth']['admin_id'];
//        $arr = [];
//        foreach ($redis->lrange($admin_id.'videoUpload',0,-1) as $value){
//            try {
//                $client = $this->initVodClient('LTAI4FcncugJ3cXhfc4TYLx3', 'oizfnpEr3XOc8lovUQBJjXDoEfu6iS');
//                $playInfo = $this->getPlayInfo($client,$value);
//                $arr[] = [
//                    'name'=>$playInfo->VideoBase->Title,
//                    'type_id'=>$type_id,
//                    'time'=>$this->ftime(gmdate('H:i:s', $playInfo->VideoBase->Duration)),
//                    'size'=>$playInfo->PlayInfoList->PlayInfo[1]->Size/1024/1024,
//                    'create_time'=>time(),
//                    'url'=>$playInfo->PlayInfoList->PlayInfo[1]->PlayURL,
//                    'ext'=>$playInfo->PlayInfoList->PlayInfo[1]->Format,
//                    'video_id'=>$value,
//                ];
//            } catch (\Exception $e) {
//                print $e->getMessage()."\n";
//            }
//        }
//        $res = model('video')->insertAll($arr);
//        if(count($redis->lrange($admin_id.'videoUpload',0,-1))==$res){
//            $redis->del($admin_id.'videoUpload');
//            $this->success('添加成功',url('admin/educloud/videoList'));
//        }else{
//            $this->error('未知错误');
//        }
//
//    }

    /**
     * 获取直播间列表
     */
    function getliveroomlist(){
        $info=$this->get_site_info(2);
        if(empty($info['partner_id'])||empty($info['partner_key'])){
            $this->redirect('admin/educloud/liveBind');
        }
        $param = $this->request->param();
        $info['limit']=config('PageSize');
        $info['page']=$param['page'];
        $url=$info['server']."/educloud/educloud/getLiveroomList";
        $LiveroomList=json_decode(post_curl($url,$info),true);
        return $this->fetch('getliveroomlist', ['list' => $LiveroomList['data']['list'],'code'=>$LiveroomList['code'],'curr'=>$param['page'],'count'=>$LiveroomList['data']['total'],'PageSize'=>config('PageSize')]);
    }
    /**
     * 删除直播间
     */
    function delLiveroom(){
        $info=$this->get_site_info(2);
        $postdata=$info;
        $postdata['room_id']=input('id');
        $url=$info['server']."/educloud/educloud/delLiveroom";
        $res=json_decode(post_curl($url,$postdata),true);
        if($res['code']==0){
            $this->success("房间删除成功！");
        }else{
            $this->error($res['msg']);
        }
    }
    /**
     * 获取回放列表
     */
    function  getplaybacklist(){
        $info=$this->get_site_info(2);
        if(empty($info['partner_id'])||empty($info['partner_key'])){
            $this->redirect('admin/educloud/liveBind');
        }
        $param = $this->request->param();
        $info['limit']=config('PageSize');
        $info['page']=$param['page'];
        $url=$info['server']."/educloud/educloud/getPlaybackList";
        $PlaybackList=json_decode(post_curl($url,$info),true);
        return $this->fetch('playbackList', ['list' => $PlaybackList['data']['list'],'code'=>$PlaybackList['code'],'curr'=>$param['page'],'count'=>$PlaybackList['data']['total'],'PageSize'=>config('PageSize')]);
    }
    /**
     * 删除回放
     */
    function delPlayback(){
        $info=$this->get_site_info(2);
        $postdata=$info;
        $postdata['room_id']=input('id');
        $url=$info['server']."/educloud/educloud/delPlayback";
        $res=json_decode(post_curl($url,$postdata),true);
        if($res['code']==0){
            $this->success("回放删除成功！");
        }else{
            $this->error($res['msg']);
        }
    }
    /**
     * 教育云短信
     */
    function cloudSMS(){

    }
    /**
     * 教育云短信签名
     */
    function signName(){
        if ($this->request->isPost()) {
            $param=$this->request->param();
            model('system')->save(['value' =>$param['SmsSign']], ['name' => 'SmsSign']);
            clear_cache();
            insert_admin_log('配置云短信签名');
            $this->success('保存成功');
        }
        $data = model('system')->where('name', 'SmsSign')->find();
        return $this->fetch('signName', ['data' => $data]);
    }
    /**
     * 教育云短信模板
     */
    function templates(){

        if ($this->request->isPost()) {
            $param=$this->request->param();
            $data=model('system')->where('name', $param['type'])->find();
            $val=unserialize($data['value']);
            if(empty($param['TemplatesId'])){
                $param['TemplatesId']=$val['TemplatesId'];
            }
            if($param['status']===null){
                $param['status']=$val['status'];
            }
            model('system')->save(['value' => serialize($param)], ['name' => $param['type']]);
            clear_cache();
            $this->success('设置成功');
        }
        $MC= model('system')->where('name', 'SmsTemplates_MC')->find();
        $SK= model('system')->where('name', 'SmsTemplates_SK')->find();
        return $this->fetch('templates', ['MC' => unserialize($MC['value']),'SK'=>unserialize($SK['value'])]);
    }
    /**
     * 上传文件函数，如过上传不成功打印$_FILES数组，查看error报错信息
     * 值：0; 没有错误发生，文件上传成功。
     * 值：1; 上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。
     * 值：2; 上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。
     * 值：3; 文件只有部分被上传。
     * 值：4; 没有文件被上传。
     * date:2018.4.18    from:zhix.net
     */
    public function uploadFile(){
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Content-type: text/html; charset=gbk32");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        $folder = input('folder');
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }
        if ( !empty($_REQUEST[ 'debug' ]) ) {
            $random = rand(0, intval($_REQUEST[ 'debug' ]) );
            if ( $random === 0 ) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }
        // header("HTTP/1.0 500 Internal Server Error");
        // exit;
        // 5 minutes execution time
        set_time_limit(5 * 60);
        // Uncomment this one to fake upload time
        usleep(5000);
        // Settings
        $targetDir = './Public'.DIRECTORY_SEPARATOR.'file_material_tmp';            //存放分片临时目录
        if($folder){
            $uploadDir = './Public'.DIRECTORY_SEPARATOR.'file_material'.DIRECTORY_SEPARATOR.$folder.DIRECTORY_SEPARATOR.date('Ymd');
        }else{
            $uploadDir = './Public'.DIRECTORY_SEPARATOR.'file_material'.DIRECTORY_SEPARATOR.date('Ymd');    //分片合并存放目录
        }
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds

        // Create target dir
        if (!file_exists($targetDir)) {
            mkdir($targetDir,0777,true);
        }
        // Create target dir
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir,0777,true);
        }
        // Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }
        $oldName = $fileName;
        $fileName = iconv('UTF-8','gb2312',$fileName);
        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        // $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory111."}, "id" : "id"}');
            }
            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }
                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }
        // Open temp file
        if (!$out = fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream222."}, "id" : "id"}');
        }
        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file333."}, "id" : "id"}');
            }
            // Read binary input stream and append it to temp file
            if (!$in = fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream444."}, "id" : "id"}');
            }
        } else {
            if (!$in = fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream555."}, "id" : "id"}');
            }
        }
        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }
        fclose($out);
        fclose($in);
        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
        $index = 0;
        $done = true;
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $redis->lPush('size',$_FILES['file']['size']);
        for( $index = 0; $index < $chunks; $index++ ) {
            if ( !file_exists("{$filePath}_{$index}.part") ) {
                $done = false;
                break;
            }
        }
        if ($done) {
            $pathInfo = pathinfo($fileName);
            $hashStr = substr(md5($pathInfo['basename']),8,16);
            $hashName = time() . $hashStr . '.' .$pathInfo['extension'];
            $uploadPath = $uploadDir . DIRECTORY_SEPARATOR .$hashName;
            if (!$out = fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream666."}, "id" : "id"}');
            }
            //flock($hander,LOCK_EX)文件锁
            if ( flock($out, LOCK_EX) ) {
                for( $index = 0; $index < $chunks; $index++ ) {
                    if (!$in = fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }
                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }
                    fclose($in);
                    unlink("{$filePath}_{$index}.part");
                }
                flock($out, LOCK_UN);
            }
            fclose($out);
            $response = [
                'success'=>true,
                'oldName'=>$oldName,
                'filePath'=>$uploadPath,
                'fileSize'=>input('size'),
                'fileSuffixes'=>$pathInfo['extension'],          //文件后缀名
                'type_id'=>$this->redisReturn()->lPop('time'),
            ];
            $arr = [
                'name'=>$response['oldName'],
                'type_id'=>$response['type_id'],
                'size'=>round($response['fileSize']/1024/1024,2),
                'create_time'=>time(),
                'url'=>'http://'.$_SERVER['SERVER_NAME'].$response['filePath'],
                'ext'=>$response['fileSuffixes'],
            ];
            $res = model('video')->insert($arr);
            return json(array_merge($response,['res'=>$res]));
        }
        // Return Success JSON-RPC response
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
    }
    public function preservation(){
        $type_id = input('type_id');
        $this->redisReturn()->lPush('time',$type_id);
        return 'success';
    }
    public function redisReturn(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        return $redis;
    }
}
